import {
  Controller,
  Get,
  Post,
  Patch,
  Query,
  Delete,
  Body,
  Param,
  Headers,
  Request,
  UseFilters,
  HttpException,
  HttpStatus,
  ParseIntPipe,
  HttpCode,
} from '@nestjs/common';
import { Response } from 'express';
import { ApiTags, ApiBearerAuth, ApiBody, ApiParam } from '@nestjs/swagger';
import { InspectionService } from './inspection.service';
import { request } from 'http';
import { signFunc } from '../../utils/sign';

@ApiBearerAuth()
@ApiTags('inspection')
@Controller('inspection')
export class InspectionController {
  constructor(private readonly inspectionService: InspectionService) {}

  @Get('vaildGet')
  vaildGet(@Query() Query, @Request() request, @Headers() token): string {
    const { originalUrl, _parsedUrl, param, header } = request;
    const timestamp = request.get('timestamp');
    const nonce = request.get('nonce');
    const sign = request.get('sign');
    const { query: queryString } = _parsedUrl;
    const serviceSign = signFunc(timestamp, decodeURI(queryString), nonce);
    return this.inspectionService.vaildGet({
      param: decodeURI(queryString),
      timestamp,
      nonce,
      fesign: sign,
      serviceSign,
    });
  }

  @Post('/vaildPost')
  vaildPost(@Request() request, @Body() body) {
    try {
      // TODO:body 为空是否使用‘{}’加密, 此处使用
      const bodyStringify = JSON.stringify(body);
      let mapSignBody = { ...body };
      if (bodyStringify !== '{}') {
        mapSignBody = {};
        // body 排序
        Object.keys(body)
          .sort()
          .forEach((keys) => {
            if (body[keys] === null) {
              mapSignBody[keys] = '';
              return;
            }
            mapSignBody[keys] =
              typeof body[keys] === 'string' || typeof body[keys] === 'number'
                ? String(body[keys])
                : body[keys];
          });
      }
      const mapSignBodyStringify = JSON.stringify(mapSignBody);
      console.log('mapSignBodyStringify:', mapSignBodyStringify);
      const timestamp = request.get('timestamp');
      const nonce = request.get('nonce');
      const sign = request.get('sign');
      const serviceSign = signFunc(timestamp, mapSignBodyStringify, nonce);
      return this.inspectionService.vaildGet({
        param: mapSignBodyStringify,
        timestamp,
        nonce,
        fesign: sign,
        serviceSign,
      });
    } catch (err) {
      throw new HttpException(
        {
          status: HttpStatus.BAD_REQUEST,
          message: '未知异常',
          error: JSON.stringify(err),
        },
        HttpStatus.BAD_REQUEST,
      );
    }
  }

  @Post('/vaildPostForm')
  vaildPostForm(@Body() body, @Request() request) {
    try {
      console.log(request);
      const bodyStringify = JSON.stringify(body);
      let mapSignBody = { ...body };
      if (bodyStringify !== '{}') {
        mapSignBody = {};
        Object.keys(body)
          .sort()
          .forEach((keys) => {
            if (keys === '_') {
              delete mapSignBody[keys];
              return;
            }
            if (body[keys] === null) {
              mapSignBody[keys] = '';
              return;
            }
            mapSignBody[keys] =
              typeof body[keys] === 'string' || typeof body[keys] === 'number'
                ? String(decodeURI(body[keys]))
                : body[keys];
          });
      }
      let mapSignBodyStringify = '';
      Object.keys(mapSignBody).forEach((keys) => {
        mapSignBodyStringify += keys;
        mapSignBodyStringify += '=';
        mapSignBodyStringify += mapSignBody[keys];
        mapSignBodyStringify += '&';
      });
      mapSignBodyStringify = mapSignBodyStringify.replace(/&$/, '');
      console.log('mapSignBodyStringify:', mapSignBodyStringify);
      const timestamp = request.get('timestamp');
      const nonce = request.get('nonce');
      const sign = request.get('sign');
      const serviceSign = signFunc(timestamp, mapSignBodyStringify, nonce);
      return this.inspectionService.vaildGet({
        param: mapSignBodyStringify,
        timestamp,
        nonce,
        fesign: sign,
        serviceSign,
      });
    } catch (err) {
      throw new HttpException(
        {
          status: HttpStatus.BAD_REQUEST,
          message: '未知异常',
          error: JSON.stringify(err),
        },
        HttpStatus.BAD_REQUEST,
      );
    }
  }
}
